<template>
  <el-dialog
    :title="formData.id ? '编辑住户' : '新增住户'"
    v-model="visible"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef" 
      label-width="120px"
      v-loading="loading"
    >
      <!-- 房户信息展示（只读） -->
      <el-divider content-position="left">房户信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="所属社区">
            <el-input v-model="householdInfo.communityName" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属楼栋">
            <el-input v-model="householdInfo.buildingName" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属单元">
            <el-input v-model="householdInfo.unitName" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="房号">
            <el-input v-model="householdInfo.roomNumber" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 住户基本信息 -->
      <el-divider content-position="left">住户基本信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="form.realName" placeholder="请输入真实姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证件类型" prop="identityType">
            <el-select v-model="form.identityType" placeholder="请选择证件类型" style="width: 100%">
              <el-option label="身份证" :value="1" />
              <el-option label="护照" :value="2" />
              <el-option label="港澳通行证" :value="3" />
              <el-option label="台湾通行证" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="身份证件号" prop="identityNo">
            <el-input v-model="form.identityNo" placeholder="请输入身份证件号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio :value="1">男</el-radio>
              <el-radio :value="2">女</el-radio>
              <el-radio :value="0">未知</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker 
              v-model="form.birthday" 
              type="date" 
              placeholder="选择出生日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学历" prop="education">
            <el-select v-model="form.education" placeholder="请选择学历" style="width: 100%">
              <el-option label="小学" value="小学" />
              <el-option label="初中" value="初中" />
              <el-option label="高中" value="高中" />
              <el-option label="大专" value="大专" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职业" prop="profession">
            <el-input v-model="form.profession" placeholder="请输入职业" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作单位" prop="workUnit">
            <el-input v-model="form.workUnit" placeholder="请输入工作单位" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="籍贯" prop="nativePlace">
            <el-input v-model="form.nativePlace" placeholder="请输入籍贯" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 紧急联系人信息 -->
      <el-divider content-position="left">紧急联系人信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="紧急联系人" prop="emergencyContact">
            <el-input v-model="form.emergencyContact" placeholder="请输入紧急联系人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="紧急联系电话" prop="emergencyPhone">
            <el-input v-model="form.emergencyPhone" placeholder="请输入紧急联系电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 其他信息 -->
      <el-divider content-position="left">其他信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="车辆信息" prop="vehicleInfo">
            <el-input v-model="form.vehicleInfo" placeholder="请输入车辆信息" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="宠物信息" prop="petInfo">
            <el-input v-model="form.petInfo" placeholder="请输入宠物信息" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="特殊需求" prop="specialNeeds">
            <el-input 
              v-model="form.specialNeeds" 
              type="textarea" 
              :rows="3"
              placeholder="请输入特殊需求"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 住户身份信息 -->
      <el-divider content-position="left">住户身份信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="住户身份" prop="residentType">
            <el-select 
              v-model="form.residentType" 
              placeholder="请选择身份"
              style="width: 100%"
            >
              <el-option label="户主" :value="1" />
              <el-option label="家庭成员" :value="2" />
              <el-option label="租客" :value="3" />
              <el-option label="临时居住" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="住户状态" prop="status">
            <el-select 
              v-model="form.status" 
              placeholder="请选择状态"
              style="width: 100%"
            >
              <el-option label="正常居住" :value="1" />
              <el-option label="已搬出" :value="0" />
              <el-option label="暂时外出" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入住日期" prop="moveInDate">
            <el-date-picker 
              v-model="form.moveInDate" 
              type="date" 
              placeholder="选择入住日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="搬出日期" prop="moveOutDate">
            <el-date-picker 
              v-model="form.moveOutDate" 
              type="date" 
              placeholder="选择搬出日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 租客信息 -->
      <div v-if="form.residentType === 3">
        <el-divider content-position="left">租约信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同开始日期" prop="contractStartDate">
              <el-date-picker 
                v-model="form.contractStartDate" 
                type="date" 
                placeholder="选择合同开始日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同结束日期" prop="contractEndDate">
              <el-date-picker 
                v-model="form.contractEndDate" 
                type="date" 
                placeholder="选择合同结束日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="月租金" prop="monthlyRent">
              <el-input-number 
                v-model="form.monthlyRent" 
                :min="0" 
                :precision="2"
                placeholder="请输入月租金"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="押金" prop="deposit">
              <el-input-number 
                v-model="form.deposit" 
                :min="0" 
                :precision="2"
                placeholder="请输入押金"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input 
                v-model="form.contractNo" 
                placeholder="请输入合同编号"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="form.remark" 
          type="textarea" 
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useResidentStore } from '@/store/resident'
import { householdApi } from '@/api/household'
import { residentApi } from '@/api/resident'

// Props
interface Props {
  visible: boolean
  formData: {
    id?: number
    residentId?: number
    residentType?: number
    moveInDate?: string
    moveOutDate?: string
    contractStartDate?: string
    contractEndDate?: string
    monthlyRent?: number
    deposit?: number
    contractNo?: string
    remark?: string
  }
  householdId?: number
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 房户信息
const householdInfo = reactive({
  communityName: '',
  buildingName: '',
  unitName: '',
  roomNumber: ''
})

// 表单数据
const form = reactive({
  // 基本信息
  realName: '',
  identityType: 1,
  identityNo: '',
  gender: 0,
  birthday: '',
  phone: '',
  email: '',
  education: '',
  profession: '',
  workUnit: '',
  nativePlace: '',
  
  // 紧急联系人
  emergencyContact: '',
  emergencyPhone: '',
  
  // 其他信息
  vehicleInfo: '',
  petInfo: '',
  specialNeeds: '',
  
  // 住户身份
  residentType: undefined as number | undefined,
  status: 1,
  moveInDate: undefined as string | undefined,
  moveOutDate: undefined as string | undefined,
  
  // 租约信息
  contractStartDate: undefined as string | undefined,
  contractEndDate: undefined as string | undefined,
  monthlyRent: undefined as number | undefined,
  deposit: undefined as number | undefined,
  contractNo: '',
  
  // 备注
  remark: ''
})

// Store
const residentStore = useResidentStore()

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单验证规则
const rules: FormRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  contractStartDate: [
    { 
      required: true, 
      message: '请选择合同开始日期', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.residentType === 3 && !value) {
          callback(new Error('租客必须填写合同开始日期'))
        } else {
          callback()
        }
      }
    }
  ],
  contractEndDate: [
    { 
      required: true, 
      message: '请选择合同结束日期', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.residentType === 3 && !value) {
          callback(new Error('租客必须填写合同结束日期'))
        } else {
          callback()
        }
      }
    }
  ],
  monthlyRent: [
    { 
      required: true, 
      message: '请输入月租金', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (form.residentType === 3 && (!value || value <= 0)) {
          callback(new Error('租客必须填写有效的月租金'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 方法
const loadHouseholdInfo = async () => {
  if (!props.householdId) return
  
  try {
    loading.value = true
    const response = await householdApi.getHouseholdDetail(props.householdId)
    if (response.code === 200 && response.data) {
      const household = response.data
      // 从后端接口获取完整的房户信息，包括社区、楼栋、单元信息
      householdInfo.communityName = household.communityName || ''
      householdInfo.buildingName = household.buildingName || ''
      householdInfo.unitName = household.unitName || ''
      householdInfo.roomNumber = household.roomNumber || ''
      
      console.log('从后端接口获取的房户信息:', household)
    }
  } catch (error) {
    console.error('加载房户信息失败:', error)
    ElMessage.error('加载房户信息失败')
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 构建提交数据（一次性完成住户创建与房户关联，避免后端校验householdId失败）
    const residentData = {
      // 基本信息
      realName: form.realName,
      identityType: form.identityType,
      identityNo: form.identityNo,
      gender: form.gender,
      birthday: form.birthday,
      phone: form.phone,
      email: form.email,
      education: form.education,
      profession: form.profession,
      workUnit: form.workUnit,
      nativePlace: form.nativePlace,
      emergencyContact: form.emergencyContact,
      emergencyPhone: form.emergencyPhone,
      vehicleInfo: form.vehicleInfo,
      petInfo: form.petInfo,
      specialNeeds: form.specialNeeds,
      status: form.status,
      
      // 住户房户关联信息（与后端ResidentAddDTO字段一致）
      householdId: props.householdId,
      residentType: form.residentType,
      moveInDate: form.moveInDate,
      moveOutDate: form.moveOutDate,
      contractStartDate: form.contractStartDate,
      contractEndDate: form.contractEndDate,
      monthlyRent: form.monthlyRent,
      deposit: form.deposit,
      contractNo: form.contractNo,
      remark: form.remark
    }
    
    if (props.formData.id) {
      // 编辑 - 先更新住户信息，再更新关联信息
      await residentStore.updateResident(props.formData.id, residentData)
      await residentStore.updateResidentHousehold(props.formData.id, householdData)
      ElMessage.success('更新成功')
    } else {
      // 新增 - 一次性创建住户并建立与房户的关联（由后端处理）
      if (!props.householdId) {
        ElMessage.error('房户ID不能为空')
        return
      }
      await residentStore.addResident(residentData)
      
      ElMessage.success('添加成功')
    }
    
    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

const handleClose = () => {
  visible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 重置表单数据
  Object.assign(form, {
    realName: '',
    identityType: 1,
    identityNo: '',
    gender: 0,
    birthday: '',
    phone: '',
    email: '',
    education: '',
    profession: '',
    workUnit: '',
    nativePlace: '',
    emergencyContact: '',
    emergencyPhone: '',
    vehicleInfo: '',
    petInfo: '',
    specialNeeds: '',
    residentType: undefined,
    status: 1,
    moveInDate: undefined,
    moveOutDate: undefined,
    contractStartDate: undefined,
    contractEndDate: undefined,
    monthlyRent: undefined,
    deposit: undefined,
    contractNo: '',
    remark: ''
  })
}

// 监听弹窗显示状态
watch(() => props.visible, (visible) => {
  if (visible) {
    // 编辑模式下，从formData中获取住户关联的房户ID
    if (props.formData.id) {
      // 编辑模式：从住户信息中获取关联的房户ID
      loadResidentHouseholdInfo(props.formData.id)
      // 同时加载住户基本信息到表单
      loadResidentBasicInfo(props.formData.id)
    } else {
      // 新增模式：使用传入的householdId
      loadHouseholdInfo()
    }
    nextTick(() => {
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    })
  }
})

// 加载住户基本信息
const loadResidentBasicInfo = async (residentId: number) => {
  try {
    const response = await residentApi.getResidentDetail(residentId)
    if (response.code === 200 && response.data) {
      const residentData = response.data
      // 将住户基本信息加载到表单中
      Object.assign(form, {
        realName: residentData.realName || '',
        identityType: residentData.identityType || 1,
        identityNo: residentData.identityNo || '',
        gender: residentData.gender || 0,
        birthday: residentData.birthday || '',
        phone: residentData.phone || '',
        email: residentData.email || '',
        education: residentData.education || '',
        profession: residentData.profession || '',
        workUnit: residentData.workUnit || '',
        nativePlace: residentData.nativePlace || '',
        emergencyContact: residentData.emergencyContact || '',
        emergencyPhone: residentData.emergencyPhone || '',
        vehicleInfo: residentData.vehicleInfo || '',
        petInfo: residentData.petInfo || '',
        specialNeeds: residentData.specialNeeds || '',
        status: residentData.status || 1
      })
    }
  } catch (error) {
    console.error('加载住户基本信息失败:', error)
    ElMessage.error('加载住户基本信息失败')
  }
}

// 加载住户关联的房户信息
const loadResidentHouseholdInfo = async (residentId: number) => {
  try {
    loading.value = true
    // 调用住户详情接口获取住户关联的房户信息
    const response = await residentApi.getResidentDetail(residentId)
    if (response.code === 200 && response.data) {
      const residentData = response.data
      // 从住户详情中获取关联的房户ID
      const householdId = residentData.householdId
      if (householdId) {
        // 使用获取到的房户ID加载房户信息
        const householdResponse = await householdApi.getHouseholdDetail(householdId)
        if (householdResponse.code === 200 && householdResponse.data) {
          const household = householdResponse.data
          // 从后端接口获取完整的房户信息，包括社区、楼栋、单元信息
          householdInfo.communityName = household.communityName || ''
          householdInfo.buildingName = household.buildingName || ''
          householdInfo.unitName = household.unitName || ''
          householdInfo.roomNumber = household.roomNumber || ''
          
          console.log('从后端接口获取的房户信息:', household)
        }
      }
    }
  } catch (error) {
    console.error('加载住户关联的房户信息失败:', error)
    ElMessage.error('加载房户信息失败')
  } finally {
    loading.value = false
  }
}

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData) {
    Object.assign(form, {
      residentType: newData.residentType,
      moveInDate: newData.moveInDate,
      moveOutDate: newData.moveOutDate,
      contractStartDate: newData.contractStartDate,
      contractEndDate: newData.contractEndDate,
      monthlyRent: newData.monthlyRent,
      deposit: newData.deposit,
      contractNo: newData.contractNo || '',
      remark: newData.remark || ''
    })
  }
}, { immediate: true, deep: true })
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

:deep(.el-divider__text) {
  font-weight: bold;
  color: #409eff;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style> 